package main

import (
	"crypto/sha1"
	"github.com/xtaci/kcp-go/v5"
	"golang.org/x/crypto/pbkdf2"
	"log"
	"time"
)

var (
	serverPass = "123456"
	serverSalt = "123"
	serverPort = "9001"
)

func main() {
	key := pbkdf2.Key([]byte(serverPass), []byte(serverSalt), 1024, 32, sha1.New)
	block, _ := kcp.NewAESBlockCrypt(key)
	if listener, err := kcp.ListenWithOptions("127.0.0.1:"+serverPort, block, 10, 3); err == nil {
		for {
			s, err := listener.AcceptKCP()
			if err != nil {
				log.Println(err)
				continue
			}
			go handleEcho(s)
		}
	} else {
		log.Fatal(err)
	}
}

func handleEcho(conn *kcp.UDPSession) {
	//读取客户端信息
	go func() {
		for {
			buf := make([]byte, 1024)
			n, err := conn.Read(buf)
			if err != nil {
				log.Println(err)
				return
			}
			log.Println("服务端收到消息：", string(buf[:n]))
		}
	}()
	for {
		msg := "服务端返回:" + conn.LocalAddr().String()
		_, err := conn.Write([]byte(msg))
		if err != nil {
			log.Println(err)
			return
		}
		time.Sleep(time.Second)
	}
}
